define(function(require,exports,module) {
    var myPub = require('./public');
    var priceCount = require('./submit_calcLastPrice');
    var couponPrice = require('./submit_coupon');


    /***************************    商家优惠   ******************************/
    var oWrap = $('.js_wrap');
    var oBusiShadow = $('.js_busiShadow');				                // 阴影
    var oCouponSeletSideBus = $('.js_couponSeletSideBus');      // 商家优惠弹框
    var oUseCouponBus = $('.js_useCouponBus');                  // 商家优惠操作入口
    var oCouponBusBtn_close = $('.js_couponBusBtn_close');      // 优惠劵关闭
    var oSubOrdCouponBus = $('.js_subOrdCouponBus');            // 提交订单 商家优惠框 (单独用)
    var oGoodsListBox = $('.js_carListBox');
    var oGoodsList = $('.js_goodsList');
    var oCarListArea = $('.js_carListArea');
    var oBusinessPay = $('.js_businessPay');
    var bSideOff = true;
    var platformBuisneCouponId = [];
    var couponPriceArr = [];
    var couponbusineId = 0;
    var couponbusinePrice = 0;
    var arrbusineArr = [];
    var ide = null;

    var buyProductList = [];                //
    var subtotalList = [];                  // 全部商品详情ID
    var $sfMember = $('.jsSFMember');       // 顺丰会员
    var sfMemberCutPrice = 0;               // 顺丰会员的 只支持商详页跳确认订单页购买
    if($sfMember.length > 0){
        var cutPrice = parseFloat($sfMember.attr("data-cutPrice"));
        if($sfMember.find('.js_memberBtn').hasClass('btn_active')){
            sfMemberCutPrice = cutPrice;
        }else{
            sfMemberCutPrice = 0;
        }
    }

    var coupon = {
        allArr : [],            // 平台通用类型优惠券
        storeArr : [],          // 指定商家类型优惠券
        cateArr : [],           // 指定分类优惠券
        goodsIdArr : [],        // 指定商品优惠券
        storeDisableArr:[],     // 指定商家不可用
        cateDisableArr:[],      // 指定分类不可用
        goodsDisableArr:[],     // 指定商品不可用
        tagArr:[],              // 指定标签能用
        // 把优惠券分类
        CouponMsg:function() {
            var _this = this;
            var oCouponEl = $('.js_coupon');
            // console.log(oCouponEl);
            var couponTypeArr = [];
            for(var i = 0;i < oCouponEl.length;i++ ){
                couponTypeArr.push(oCouponEl.eq(i).attr('data-limitType'))
            }
            for(var j = 0;j<couponTypeArr.length;j++){
                var obj = {};
                var oCouponTy = oCouponEl.eq(j);
                var nSwitch = couponTypeArr[j]*1;
                switch(nSwitch){
                    case 0:
                        obj.limitType = 0;                                                  // 优惠券类型
                        obj.couponId = oCouponTy.attr('data-couponId');                     // 优惠券Id
                        obj.limitPlatPrice = oCouponTy.find('.js_threshold').text()*1;      // 优惠券使用限制金额
                        obj.usePlatPricePrice = oCouponTy.find('.js_costPrice').text()*1;   // 优惠券金额
                        _this.allArr.push(obj);
                        break;
                    case 1:
                        obj.limitType = 1;                                                  // 优惠券类型
                        obj.goodsArr = oCouponTy.attr('data-supplierSet');                  // 对应的商家Id
                        obj.couponId = oCouponTy.attr('data-couponId');                     // 优惠券Id
                        obj.limitPlatPrice = oCouponTy.find('.js_threshold').text()*1;      // 优惠券使用限制金额
                        obj.usePlatPrice = oCouponTy.find('.js_costPrice').text()*1;        // 优惠券金额
                        _this.storeArr.push(obj);
                        break;
                    case 2:
                        obj.limitType = 2;                                                  // 优惠券类型
                        obj.goodsArr = oCouponTy.attr('data-categorySet');                  // 对应的分类Id
                        obj.couponId = oCouponTy.attr('data-couponId');                     // 优惠券Id
                        obj.limitPlatPrice = oCouponTy.find('.js_threshold').text()*1;      // 优惠券使用限制金额
                        obj.usePlatPrice = oCouponTy.find('.js_costPrice').text()*1;        // 优惠券金额
                        _this.cateArr.push(obj);
                        break;
                    case 3:
                        obj.limitType = 3;                                                  // 优惠券类型
                        obj.goodsArr = oCouponTy.attr('data-goodsSet');                     // 对应的商品Id
                        obj.couponId = oCouponTy.attr('data-couponId');                     // 优惠券Id
                        obj.limitPlatPrice = oCouponTy.find('.js_threshold').text()*1;      // 优惠券使用限制金额
                        obj.usePlatPrice = oCouponTy.find('.js_costPrice').text()*1;        // 优惠券金额
                        _this.goodsIdArr.push(obj);
                        break;
                    case 4:
                        obj.limitType = 4;                                                  // 优惠券类型
                        obj.goodsArr = oCouponTy.attr('data-goodsSet');                     // 对应的商品Id
                        obj.couponId = oCouponTy.attr('data-couponId');                     // 优惠券Id
                        obj.limitPlatPrice = oCouponTy.find('.js_threshold').text()*1;      // 优惠券使用限制金额
                        obj.usePlatPrice = oCouponTy.find('.js_costPrice').text()*1;        // 优惠券金额
                        _this.goodsDisableArr.push(obj);
                        break;
                    case 5:
                        obj.limitType = 5;                                                  // 优惠券类型
                        obj.goodsArr = oCouponTy.attr('data-supplierSet');                  // 对应的商家Id
                        obj.couponId = oCouponTy.attr('data-couponId');                     // 优惠券Id
                        obj.limitPlatPrice = oCouponTy.find('.js_threshold').text()*1;      // 优惠券使用限制金额
                        obj.usePlatPrice = oCouponTy.find('.js_costPrice').text()*1;        // 优惠券金额
                        _this.storeDisableArr.push(obj);
                        break;
                    case 6:
                        obj.limitType = 6;                                                  // 优惠券类型
                        obj.goodsArr = oCouponTy.attr('data-categorySet');                  // 对应的分类Id
                        obj.couponId = oCouponTy.attr('data-couponId');                     // 优惠券Id
                        obj.limitPlatPrice = oCouponTy.find('.js_threshold').text()*1;      // 优惠券使用限制金额
                        obj.usePlatPrice = oCouponTy.find('.js_costPrice').text()*1;        // 优惠券金额
                        _this.cateDisableArr.push(obj);
                        break;
                    case 7:
                        obj.limitType = 7;                                                  // 优惠券类型
                        obj.goodsArr = oCouponTy.attr('data-goodsLabel');                   // 对应的分类Id
                        obj.couponId = oCouponTy.attr('data-couponId');                     // 优惠券Id
                        obj.limitPlatPrice = oCouponTy.find('.js_threshold').text()*1;      // 优惠券使用限制金额
                        obj.usePlatPrice = oCouponTy.find('.js_costPrice').text()*1;        // 优惠券金额
                        _this.tagArr.push(obj);
                        break;
                    default:
                        break;
                }
            }
        },
        // 算出确认订单页面适用各个优惠券的原价
        CostPrice:function () {
            var _this = this;
            _this.allArr = [];
            _this.storeArr = [];
            _this.cateArr = [];
            _this.goodsIdArr = [];
            _this.storeDisableArr = [];
            _this.cateDisableArr = [];
            _this.goodsDisableArr = [];
            _this.tagArr = [];
            _this.CouponMsg();
            /*console.log('allArr',_this.allArr);
            console.log('storeArr',_this.storeArr);
            console.log('cateArr',_this.cateArr);
            console.log('goodsIdArr',_this.goodsIdArr);
            console.log('storeDisableArr',_this.storeDisableArr);
            console.log('cateDisableArr',_this.cateDisableArr);
            console.log('goodsDisableArr',_this.goodsDisableArr);
            console.log('tagArr',_this.tagArr);*/

            _this.CostMethods(_this.allArr,'',false);
            _this.CostMethods(_this.storeArr,'supplierId',false);
            _this.CostMethods(_this.cateArr,'categoryId',false);
            _this.CostMethods(_this.goodsIdArr,'goodsId',false);
            _this.CostMethods(_this.storeDisableArr,'supplierId',true);
            _this.CostMethods(_this.cateDisableArr,'categoryId',true);
            _this.CostMethods(_this.goodsDisableArr,'goodsId',true);
            _this.CostArrMethods(_this.tagArr);
        },

        // 计算标签优惠券
        CostArrMethods:function (arr) {
            var _this = this;
            for(var n = 0;n < arr.length;n++){
                var couponLabel = arr[n].goodsArr.replace('[','').replace(']','').replace(/\s/g,'');
                var nPriceTol = 0;
                var nBusPriceTol = 0;
                if(couponLabel.indexOf(',') > -1){
                    couponLabel = couponLabel.split(',')
                }else{
                    if(couponLabel != undefined && couponLabel.length>0){
                        couponLabel = [couponLabel]
                    }else{
                        couponLabel = []
                    }
                }
                for(var i = 0;i < subtotalList.length;i++){
                    var labelArr = subtotalList[i][0].goodsLabelId.replace('[','').replace(']','').replace(/\s/g,'');
                    var nPriceLim = 0;
                    var nbusLim = 0;
                    var canUse = [];
                    if(labelArr.indexOf(',') > -1){
                        labelArr = labelArr.split(',')
                    }else{
                        if(labelArr != undefined && labelArr.length>0){
                            labelArr = [labelArr]
                        }else{
                            labelArr = []
                        }
                    }
                    canUse = couponLabel.filter(function (v) {
                        return labelArr.indexOf(v) !== -1
                    });
                    if(canUse.length > 0){
                        nPriceLim = (subtotalList[i][0].quantity*1)*(subtotalList[i][0].price*1);
                        nbusLim = subtotalList[i][0].busPrice*1;
                    }
                    nPriceTol += nPriceLim;
                    nBusPriceTol += nbusLim;
                }
                arr[n].oldPrice = nPriceTol - sfMemberCutPrice;                // 适用该优惠券的所有商品价格
                arr[n].BusConPrice = nBusPriceTol;          // 适用该优惠券的所有商品使用商家优惠券的价格
            }
        },

        // 计算其他类型优惠券
        CostMethods: function (arr, pe, isDisable) {
            var _this = this;
            for(var i = 0;i < arr.length;i++){
                if (pe == '') {
                    var nPrice = 0;
                    var nBuslimPrice = 0;
                    for (var b = 0; b < subtotalList.length; b++) {
                        var nAllPrice = 0;
                        var nAllBusPrice = 0;
                        nAllPrice = (subtotalList[b][0].quantity * 1) * (subtotalList[b][0].price * 1);
                        nAllBusPrice = subtotalList[b][0].busPrice * 1;
                        nPrice += nAllPrice;                // 适用该优惠券的所有商品价格
                        nBuslimPrice += nAllBusPrice;       // 适用该优惠券的所有商品使用商家优惠券的价格
                    }
                    arr[i].oldPrice = nPrice - sfMemberCutPrice;
                    arr[i].BusConPrice = nBuslimPrice;
                } else {
                    var nArr = arr[i].goodsArr.replace('[', '').replace(']', '');
                    var goodsIdStore = [];
                    var nPriceTol = 0;
                    var nBusPriceTol = 0;
                    var disArr = [];        // 放指定不可用类型的优惠券 的可用商品
                    if (nArr.indexOf(',') > -1) {
                        goodsIdStore = nArr.split(',')
                    } else {
                        goodsIdStore = [nArr]
                    }
                    for (var j = 0; j < goodsIdStore.length; j++) {
                        for (var n = 0; n < subtotalList.length; n++) {
                            var nPriceLim = 0;
                            var nbusLim = 0;
                            var type = null;
                            switch (pe) {
                                case 'supplierId':
                                    type = subtotalList[n][0].supplierId * 1;
                                    break;
                                case 'categoryId':
                                    type = subtotalList[n][0].categoryId * 1;
                                    break;
                                case 'goodsId':
                                    type = subtotalList[n][0].goodsId * 1;
                                    break;
                                case 'supplierDisableId':
                                    type = subtotalList[n][0].supplierId * 1;
                                    break;
                                case 'categoryDisableId':
                                    type = subtotalList[n][0].categoryId * 1;
                                    break;
                                case 'goodsDisableId':
                                    type = subtotalList[n][0].goodsId * 1;
                                    break;
                                default:
                                    break;
                            }
                            if (isDisable) {
                                if (goodsIdStore[j] * 1 !== type) {
                                    if (disArr.indexOf(subtotalList[n][0]) == -1) {
                                        disArr.push(subtotalList[n][0]);
                                        nPriceLim = (subtotalList[n][0].quantity * 1) * (subtotalList[n][0].price * 1);
                                        nbusLim = subtotalList[n][0].busPrice * 1;
                                    }
                                }
                            } else {
                                if (goodsIdStore[j] * 1 === type) {
                                    nPriceLim = (subtotalList[n][0].quantity * 1) * (subtotalList[n][0].price * 1);
                                    nbusLim = subtotalList[n][0].busPrice * 1;
                                }
                            }

                            nPriceTol += nPriceLim;
                            nBusPriceTol += nbusLim;
                        }
                    }
                    arr[i].oldPrice = nPriceTol - sfMemberCutPrice;                // 适用该优惠券的所有商品价格
                    arr[i].BusConPrice = nBusPriceTol;          // 适用该优惠券的所有商品使用商家优惠券的价格
                }
            }
        },

        // 商家优惠劵分类判断
        priceScale: function (storeCoupons) {
            var _this = this;
            // 使用商家优惠劵
            if(storeCoupons) {
                // [28625, 28626, 28632]

                switch (storeCoupons.couponLimitType)  {
                    // 全场通用
                    case 0:
                        // console.log('couponLimitType=0',storeCoupons)
                        _this.setGoodsListInfo(storeCoupons);
                        break;
                    // 指定商品
                    case 3:
                        // console.log('couponLimitType=3',storeCoupons)
                        _this.setGoodsListInfo(storeCoupons);
                        break;
                    // 指定不可使用商品
                    case 4:
                        // console.log('couponLimitType=4',storeCoupons)
                        _this.setGoodsListInfo(storeCoupons, 'reverse');
                        break;
                    default:

                        break;
                }
                _this.setBusPrice();

            }
            // 没有使用
            else {}
        },

        // 获取相同id的商家产品list
        setGoodsListInfo: function(data, type) {
            var _this = this;
            var arrPrice = [];
            var $tarId = [];
            var sum = 0;
            var _reducePrice = [];
            for(var i=0; i<subtotalList.length; i++) {
                var _List = subtotalList[i][0];
                // 匹配商家
                if(data.supplierId == _List.supplierId) {
                    _this.setOfferPrice(data, _List, type,function (price, elemt) {
                        arrPrice.push(price);
                        $tarId.push(elemt);
                    });

                }
            }

            sum = _this.arrSum(arrPrice);
            // console.log('sum', sum)

            for (var n=0; n<arrPrice.length; n++) {
                // console.log(arrPrice[n]/sum * data.couponPrice)
                // console.log(( Math.round( arrPrice[n]/sum * data.couponPrice * 100 )/100 ).toFixed(2))
                var reducePrice = ( Math.round( arrPrice[n]/sum * data.couponPrice * 100 )/100 ).toFixed(2);
                _reducePrice.push(reducePrice);
                // 最有上面循环完成可执行
                if( n == arrPrice.length-1 ) {
                    oCarListArea.each(function (k) {
                        if( $(this).attr('data-goodsid')*1 == $tarId[k] ) {
                            // 如果后面的价格大于优惠劵价格
                            if(_this.arrSum(_reducePrice) > data.couponPrice ) {
                                // oCarListArea.find('.js_goodsPrice').eq(oCarListArea.length-1).attr('data-reducePrice', _reducePrice[n])
                                oCarListArea.find('.js_goodsPrice').eq(oCarListArea.length-1).attr('data-reducePrice', data.couponPrice)
                            }
                            else {
                                // console.log(k,$tarId )
                                // 设置最后减过优惠的价格
                                $(this).find('.js_goodsPrice').attr('data-reducePrice', _reducePrice[k]);
                            }
                        }
                    });
                }
            }
        },

        setOfferPrice: function(arrlist, val, type, fn) {
            var arrCouponGoodsSet = arrlist.couponGoodsSet;
            var valGoodsId = val.goodsId * 1;
            var _count = 0;
            // console.log('arrCouponGoodsSet', arrCouponGoodsSet)
            // 全场通用
            if(arrCouponGoodsSet == '') {
                if(fn)fn(val.price * val.quantity, valGoodsId)
            }
            else {
                // 指定商品可用
                if(!type) {
                    for(var i=0; i<arrCouponGoodsSet.length; i++) {
                        if(arrCouponGoodsSet[i] * 1 == valGoodsId) {
                            // console.log(val)
                            if(fn)fn(val.price * val.quantity, valGoodsId);
                        }
                    }
                }
                // 指定商品 不可用
                else {
                    for(var i=0; i<arrCouponGoodsSet.length; i++) {
                        if(arrCouponGoodsSet[i] * 1 != valGoodsId) {
                            // console.log(val)
                            _count++;
                        }
                    }
                    // 只记录商品统计次数到最大值 才能进行回调操作
                    if(_count == arrCouponGoodsSet.length) {
                        if(fn)fn(val.price * val.quantity, valGoodsId);
                    }

                }

            }
        },

        // 数组求和
        arrSum: function(arr) {
            var s=0;
            if(arr.length==0){
                return 0;
            }
            else if(arr.length==1){
                return arr[0];
            }
            else{
                for(var i=0;i<arr.length;i++){
                    s+=arr[i]*1;
                }
                return s;
            }
        },

        // 设置优惠劵
        initCoupons: function () {
            var _this = this;
            // console.log('coupon_business', _this.storeDisableArr);
            // console.log('coupon_business', _this.cateDisableArr);
            // console.log('coupon_business', _this.goodsDisableArr);
            _this.CostPrice();
            priceCount.initAllPrice();

            couponPrice.couponchooseShow([_this.cateArr,_this.storeArr,_this.allArr,_this.tagArr,_this.goodsIdArr,_this.storeDisableArr,_this.cateDisableArr,_this.goodsDisableArr], function () {
                priceCount.useBuisneCouponPrice(platformBuisneCouponId,couponPriceArr);
            });
        },
        // 设置商家优惠券等比例减后价格
        setBusPrice: function () {
            var nReduceprice = 0;
            for(var i=0; i<subtotalList.length; i++) {
                nReduceprice = oGoodsList.find('.js_goodsPrice').eq(i).attr('data-reduceprice') * 1;
                subtotalList[i][0].busPrice = nReduceprice;
            }
        }
    };
    exports.coupon = coupon;

    oUseCouponBus.each(function () {
        var _this = $(this);
        var moveHeight = _this.siblings('.js_couponSeletSideBus').outerHeight(true);     //商家优惠高度
        _this.siblings('.js_couponSeletSideBus').css({'bottom': -moveHeight });
        // 商家优惠使用 显示优惠券
        _this.hammer().on('tap', function () {
            if(!bSideOff)  return;
            bSideOff = false;
            oWrap.addClass('businesWrap');
            _this.siblings('.js_subOrdCouponBus').show().stop().animate({ 'bottom':0 },300,function() {
                _this.siblings('.js_busiShadow').show();
                bSideOff = true;
            });
            myPub.HamstopPropaga();
        });

        _this.siblings('.js_busiShadow').hammer().on('tap', function (e) {
            // 点击阴影隐藏优惠券
            _this.siblings('.js_subOrdCouponBus').stop().animate({bottom:-moveHeight},300,function(){
                oWrap.removeClass('businesWrap');
                _this.siblings('.js_subOrdCouponBus').hide();
                _this.siblings('.js_busiShadow').hide();
                bSideOff = true
            });
            e.stopPropagation();
        });

        _this.siblings('.js_subOrdCouponBus').find('.js_couponBusBtn_close').hammer().on('tap', function (e) {
            // 点击确定按钮隐藏优惠券
            $(this).parents('.js_couponSeletSideBus').stop().animate({
                bottom: -moveHeight
            },300,function(){
                oWrap.removeClass('businesWrap');
                $(this).hide();
                $(this).siblings('.js_busiShadow').hide();
                bSideOff = true
            });
           // myPub.HamstopPropaga();
            e.stopPropagation();
        });

    });

    // 获取商品数据
    GetGoodsList();
    function GetGoodsList() {
        oGoodsList.find('li').each(function () {
            var $goodsLi = $(this);
            var supplierId = $goodsLi.parents('.js_carListBox').find('.js_storeOwner').attr("data-supplierId") * 1;
            var $goodsArea = $goodsLi.find('.js_carListArea');
            var goodsId = parseInt($goodsArea.attr("data-goodsId"));
            var productId = parseInt($goodsArea.attr("data-productId"));
            var goodsFinalPrice = parseFloat($goodsArea.find('.js_goodsPrice').attr("data-finalPrice"));
            var goodsCategoryId = parseFloat($goodsArea.attr("data-categoryId"));
            var goodsLabelId = $goodsArea.attr("data-goodsLabel");
            var quantity = parseInt($goodsArea.find('.js_quantity').attr("data-quantity"));
            $goodsLi.find('.js_goodsPrice').attr('data-reducePrice', 0);
            var busPrice = parseFloat($goodsArea.find('.js_goodsPrice').attr("data-reduceprice"));
            var buyProduct = {
                supplierId:supplierId,
                goodsId:goodsId,
                productId:productId,
                quantity:quantity,
                price:goodsFinalPrice,
                categoryId:goodsCategoryId,
                busPrice:busPrice,
                goodsLabelId:goodsLabelId
            };
            buyProductList.push(buyProduct);
            subtotalList.push(buyProductList);

            buyProductList = [];
        });
    }
    exports.GetGoodsList = GetGoodsList;
    // console.log(subtotalList);

    busChooseOptimal();
    // 商家优惠券 开始最优选择
    function busChooseOptimal() {
        var nSFMemberJifen = 0;
        var nSFMemberOff = false;
        couponPriceArr = [];
        platformBuisneCouponId = [];
        if($sfMember.length > 0){
            var oGoodsPrice = $('.js_goodsPrice').attr("data-finalprice") * 1 *($('.js_quantity').attr("data-quantity"));
            nSFMemberJifen = oGoodsPrice - sfMemberCutPrice;
        }
        oGoodsListBox.each(function (n, el) {
            // 商家ID
            var nSupplierId = $(this).find('.js_storeOwner').attr("data-supplierId") * 1;
            // 商家券使用限制额度
            var oGoodsBusLimit = $(el).find('.js_busConponLimit');
            // 默认选中最大的值的优惠券
            var w =  $(el).find('.js_busConpon');
            // 商家优惠劵 id， 优惠劵部分数据
            var couponId, jsonStoreCoupon, couponGoodsSet;
            var couponPrice = 0;
            var oBusinessPay = $(el).find('.js_businessPay');
            if (w.length > 0) {

                var max = w.eq(0).find('.js_busniConponPrice').text()*1;
                var index = 0;
                for(var i=0;i<w.length;i++){
                    if($sfMember.length > 0){
                        if((nSFMemberJifen - oGoodsBusLimit.eq(i).text()*1) < 0){
                            oBusinessPay.text('不使用');
                            oBusinessPay.attr('data-businePrice',0);
                            oBusinessPay.addClass('busineCouDollor');
                            w.eq(i).parent('li').addClass('hideBusSFCou');
                            index = null;
                        }else{
                            if(w.eq(i).find('.js_busniConponPrice').text()*1 > max){
                                max = w.eq(i).find('.js_busniConponPrice').text();
                                index = i;
                            }
                        }
                    }else{
                        if(w.eq(i).find('.js_busniConponPrice').text()*1 > max){
                            max = w.eq(i).find('.js_busniConponPrice').text();
                            index = i;
                        }
                    }

                }
                if(index != null){
                    nSFMemberOff = true;
                    w = w.eq(index);
                    couponId = w.attr("couponBuisId");
                    couponPrice = w.find('.js_busniConponPrice').text();


                    if(w.attr("data-goodsSet") !== undefined) {
                        // 商家id supplierId, conpon.find('.js_goodsPrice').attr('data-reducePrice', 0);
                        // 商家优惠劵 couponId，
                        // 指定商品数组 couponGoodsSet，
                        // 设置条件 couponLimitType，
                        // 优惠劵面值价格 couponPrice
                        var _arr = [];
                        couponGoodsSet = w.attr("data-goodsSet").replace(/\s*/g,"").replace('[','').replace(']','');
                        couponGoodsSet.indexOf(',') > -1 ? _arr = couponGoodsSet.split(',') : _arr.push(couponGoodsSet);

                        jsonStoreCoupon = {
                            'supplierId': nSupplierId,
                            'couponId': couponId*1,
                            'couponGoodsSet': _arr,
                            'couponLimitType': w.attr("data-limitType")*1,
                            'couponPrice': couponPrice*1
                        };

                        coupon.priceScale(jsonStoreCoupon);
                    }
                }
            }else{
                nSFMemberOff = true;
                couponId = 0;
                couponPrice = 0;
            }
            if(nSFMemberOff){
                w.addClass('active');
                oBusinessPay.text('-￥'+couponPrice);
                oBusinessPay.attr('data-businePrice',couponPrice);
                oBusinessPay.removeClass('busineCouDollor');
                couponPriceArr.push(couponPrice);
                platformBuisneCouponId.push(couponId);

                couponId = null;
                jsonStoreCoupon = null;
                couponGoodsSet = null;
                w = null;
            }

        });
    }
    exports.busChooseOptimal = busChooseOptimal;

    // 商家优惠点击选择
    oSubOrdCouponBus.find('li').hammer().on('tap', function () {
        var $parentGoodslist = $(this).parents('.js_carListBox');
        var $parent = $(this).parents('.js_subOrdCouponBus');       // 优惠劵弹框
        var oCarListBox = $(this).parents('.js_carListBox');        // 商家的一整块区域
        var oBusConpon = $(this).find('.js_busConpon');                 // 找到对应的优惠券
        var supplierId = parseInt(oCarListBox.find('.js_storeOwner').attr("data-supplierId"));  //商家的Id
        var nbusniPrice = $(this).find('.js_busniConponPrice').text()*1;  // 商家优惠劵价格
        var sLimitPrice = $(this).find('.js_busConponLimit').text()*1;  // 商家优惠劵价格
        var index = couponIndex(supplierId);            // 商家索引
        var totalPrice = $parent.siblings('.js_subPrice').find('.js_calSum').attr('data-calsum')*1 ;    // 这个商家的商品价格总和
        var oBusinessPay = $parent.siblings('.js_useCouponBus').find('.js_businessPay');        // 优惠劵使用展示信息

        $(this).siblings().find('.js_busConpon').removeClass('active');

        var jsonStoreCoupon = {};
        var couponId, couponGoodsSet, couponPrice;

        if(oBusConpon.hasClass('active')){
            // 没有选择优惠劵
            oBusConpon.removeClass('active');
            nbusniPrice = 0;
            setPriceText(function () {
                // 获取选择的信息
                platformBuisneCouponId[index] = 0;
                couponPriceArr[index] = 0;
            });

            $parentGoodslist.find('.js_goodsPrice').attr('data-reducePrice', 0);
            coupon.setBusPrice();


        }else{
            // 选择一个优惠劵
            oBusConpon.addClass('active');
            nbusniPrice = $(this).find('.js_busniConponPrice').text();
            couponbusineId = $(this).find('.js_busConpon').attr("couponBuisId");
            setPriceText(function () {
                // 获取选择的信息
                platformBuisneCouponId[index] = couponbusineId;
                couponPriceArr[index] = nbusniPrice;
            });

            if(oBusConpon.attr("data-goodsSet") !== undefined) {
                couponPrice = oBusConpon.find('.js_busniConponPrice').text();
                $parentGoodslist.find('.js_goodsPrice').attr('data-reducePrice', 0);
                // 商家id supplierId,
                // 商家优惠劵 couponId，
                // 指定商品数组 couponGoodsSet，
                // 设置条件 couponLimitType，
                // 优惠劵面值价格 couponPrice
                var _arr = [];
                couponId = oBusConpon.attr("couponBuisId");
                couponGoodsSet = oBusConpon.attr("data-goodsSet").replace(/\s*/g,"").replace('[','').replace(']','');
                couponGoodsSet.indexOf(',') > -1 ? _arr = couponGoodsSet.split(',') : _arr.push(couponGoodsSet);


                jsonStoreCoupon = {
                    'supplierId': supplierId,
                    'couponId': couponId*1,
                    'couponGoodsSet': _arr,
                    'couponLimitType': oBusConpon.attr("data-limitType")*1,
                    'couponPrice': couponPrice*1
                };
                coupon.priceScale(jsonStoreCoupon);
            }

        }






        //设置页面 商家优惠信息
        function setPriceText(fn) {
            if(totalPrice < sLimitPrice){
                oBusinessPay.text('不使用');
                oBusinessPay.attr('data-businePrice',0);
                oBusinessPay.addClass('busineCouDollor');
                myPub.TipLayer('此优惠券不可用','no',function () {},2);
                oBusConpon.removeClass('active');
                $parentGoodslist.find('.js_goodsPrice').attr('data-reducePrice', 0);
            }
            else if(nbusniPrice == 0) {
                oBusinessPay.text('不使用');
                oBusinessPay.attr('data-businePrice', nbusniPrice);
                oBusinessPay.addClass('busineCouDollor');
            }
            else {
                oBusinessPay.text('-￥'+nbusniPrice);
                oBusinessPay.attr('data-businePrice',nbusniPrice);
                oBusinessPay.removeClass('busineCouDollor');
            }
            if(fn)fn();
        }


        coupon.initCoupons();

        myPub.HamstopPropaga();

    });

    // coupon.CostPrice();
    coupon.initCoupons();

    // 判断商家的下标
    function couponIndex(index) {
        arrbusineArr=[];
        $('.js_storeOwner').each(function () {
            arrbusineArr.push($(this).attr('data-supplierid'));
        });
        for(var i = 0;i < arrbusineArr.length; i++){
            if(arrbusineArr[i] == index){
                ide = i;
            }
        }

        return ide
    }

});